<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <i class="el-icon-info" />
          <span>总记录数:{{ total }}条</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button
            v-if="$checkPoint('import-excel')"
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >导入excel</el-button>
          <el-button
            v-if="$checkPoint('export-excel')"
            type="danger"
            size="small"
            :loading="isLoading"
            @click="handleDownloadFn"
          >导出excel</el-button>
          <el-button type="primary" size="small" @click="addFn">新增员工</el-button>
        </template>
      </page-tools>
      <el-card>
        <el-table
          :data="list"
          border
          style="width: 100%"
          :default-sort="{prop: 'workNumber'}"
        >
          <el-table-column
            fixed
            type="index"
            label="序号"
            width="50"
          />
          <el-table-column
            fixed
            prop="username"
            label="姓名"
            width="120"
          />
          <el-table-column
            fixed
            prop="staffPhoto"
            label="头像"
            width="120"
          >
            <template slot-scope="scope">
              <image-holder :url="scope.row.staffPhoto" style="width:80px" />
            </template>
          </el-table-column>
          <el-table-column
            prop="workNumber"
            label="工号"
            width="140"
            sortable
          />
          <el-table-column
            label="聘用方式"
            width="140"
          >
            <template slot-scope="scope">
              {{ formOfEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="departmentName"
            label="部门"
            width="150"
          />
          <el-table-column
            prop="timeOfEntry"
            label="入职时间"
            width="200"
            sortable
          >
            <template slot-scope="scope">
              {{ timeOfEntry(scope.row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="assignRoleFn(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delFn(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-pagination
        layout="prev, pager, next"
        :total="total"
        :page-size="params.size"
        @current-change="currentChange"
      />
      <el-dialog
        title="新增员工"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
        @close="closeFn"
      >
        <addEmployee
          ref="addEmployee"
          @offFn="dialogFormVisible=false"
          @addEmployee="employeeSimpleFn"
        />
      </el-dialog>

      <el-dialog
        title="分配角色"
        :visible.sync="dialogRole"
        :close-on-click-modal="false"
      >
        <assignRole
          v-if="dialogRole"
          :user-id="curEmployeId"
          @closeRole="dialogRole=false"
        />
      </el-dialog>
    </div>

  </div>
</template>

<script>
import { reqGetEmployeeListAPI, delEmployeeAPI } from '@/api/employees'
import addEmployee from './addEmployee'
import assignRole from './assignRole'
// 引入枚举-------------------策略模式
import EmployeeEnum from '@/constant/employees'
// 定义一个新的对象
const hireType = {}
// 把枚举的数据循环遍历,把数据里的id作为新对象的键,把数据里的value作为新的数据
EmployeeEnum.hireType.forEach(item => {
  hireType[item.id] = item.value
})
export default {
  components: {
    addEmployee,
    assignRole
  },
  data() {
    return {
      list: [],
      total: 0,
      params: {
        size: 5,
        page: 1
      },
      dialogFormVisible: false,
      isLoading: false,
      dialogRole: false, // 控制分配角色的弹窗显示和隐藏
      curEmployeId: ''
    }
  },
  created() {
    // 1 创建页面的时候,请求数据,铺设页面
    this.employeeSimpleFn()
  },
  methods: {
    transDate(arr) {
      const header = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const first = arr[0]
      const headers = Object.keys(first).map(item => header[item])
      console.log('得到的表头是', headers)
      const values = arr.map(obj => {
        // 聘用形式的转换,看看obj里面有没有这个属性
        if ('formOfEmployment' in obj) {
          // obj.formOfEmployment 原来是1，2； 要改成 '正式','非正式'
          obj.formOfEmployment = hireType[obj.formOfEmployment]
        }
        return Object.values(obj)
      })
      console.log('数据是', values)
      return { headers, values }
    },
    // 点击导出excel表格 ,保存到本地
    handleDownloadFn() {
      // 懒加载方式的一种
      import('@/vendor/Export2Excel').then(async excel => {
        // 请求数据之前开启loading
        this.isLoading = true
        // 1请求数据
        const res = await reqGetEmployeeListAPI(this.params)
        const { headers, values } = this.transDate(res.rows)
        excel.export_json_to_excel({
          header: headers, // 导出数据的表头 默认值是[]
          data: values, // 导出具体的数据    默认值是[[]]
          filename: 'Excel', // 导出的文件名
          autoWidth: true, // 导出的内容是否要自适应宽度  默认是true
          bookType: 'xlsx' // 导出文件类型    默认值是xlsx
        })
        // 请求结束之后,关闭loading
        this.isLoading = false
      })
    },
    // 关闭弹层,清空子组件的数据和校验结果
    closeFn() {
      this.$refs.addEmployee.closeFn()
    },
    async employeeSimpleFn() {
      // 2 请求数据
      const res = await reqGetEmployeeListAPI(this.params)
      // 3 赋值
      this.list = res.rows
      this.total = res.total
      console.log(res)
    },
    // 用户点击了增加用户
    addFn() {
      this.dialogFormVisible = true
    },
    // 调用删除接口
    async  delEmployeeFn(id) {
      const res = await delEmployeeAPI(id)
      console.log(res)
      // 判断当前页面的数据还剩一个的时候,继续删除的话,让当前页面减1
      if (this.list.length === 1) {
        this.params.page--
        // 当所有的数据都删除完毕后,不可能给后台发送page为0
        if (this.params.page === 0) {
          this.params.page = 1
        }
      }
      // 刷新页面
      this.employeeSimpleFn()
    },
    // 用户点击了删除按钮
    delFn(id) {
      this.$confirm('此操作将永久删除该员工信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delEmployeeFn(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 页码变化时触发的方法
    currentChange(newPage) {
      this.params.page = newPage
      this.employeeSimpleFn()
    },
    // 对后端返回的类型的编码进行翻译 ，还原成 中文
    formOfEmployment(id) {
      return hireType[id]
    },
    timeOfEntry(time) {
      // console.log(time)
      // const Y = new Date(time).getFullYear()
      // const M = new Date(time).getMonth() + 1
      // const D = new Date(time).getDate()
      // return `${Y}-${M}-${D}`
      // 因为是字符串,截取前面10个
      return time.substr(0, 10)
    },
    // 分配角色方法
    assignRoleFn(id) {
      this.dialogRole = true
      this.curEmployeId = id
    }
  }

}
</script>

<style scoped>
i {
  margin-right: 10px;
  color: #409eff;
    }
</style>
